package cn.hcbycloud.auth.front.controller;


import cn.hcbycloud.auth.bo.LoginSuccessResultBO;
import cn.hcbycloud.auth.front.converter.FrontLoginConverter;
import cn.hcbycloud.auth.front.dto.FrontUserPasswordLoginRequestDTO;
import cn.hcbycloud.auth.front.dto.FrontUserPasswordLoginResponseDTO;
import cn.hcbycloud.auth.front.dto.FrontUserPasswordLoginWithImgCodeRequestDTO;
import cn.hcbycloud.auth.service.UserLoginService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author gaoh
 * @desc 认证web层
 * @date 2022年01月27日 下午 10:18
 */
@RestController
@RequestMapping("/front/login")
@AllArgsConstructor
public class FrontLoginController {
    private FrontLoginConverter frontLoginConverter;
    private UserLoginService userLoginService;

    /**
     * 用户名密码认证，兼容图片验证码校验逻辑
     *
     * @param requestDTO
     * @return
     */
    @PostMapping(value = {"/user/{tenantCode}"})
    public FrontUserPasswordLoginResponseDTO login(@Valid @PathVariable("tenantCode") String tenantCode,
                                                   @RequestBody FrontUserPasswordLoginRequestDTO requestDTO) {
        LoginSuccessResultBO loginSuccessResultBO = userLoginService.getJwtToken(requestDTO.getUserName(),
                requestDTO.getPassword(), tenantCode);
        return frontLoginConverter.modelToResponse(loginSuccessResultBO);
    }

    @PostMapping(value = {"/user/{tenantCode}/{imageCode}/{randomCode}"})
    public FrontUserPasswordLoginResponseDTO login(@Valid @PathVariable("tenantCode") String tenantCode,
                                                   @PathVariable("imageCode") String imageCode,
                                                   @PathVariable("randomCode") String randomCode,
                                                   @RequestBody FrontUserPasswordLoginWithImgCodeRequestDTO requestDTO) {
        /* 如参数中图片验证码不为空，需要首先进行校验*/
        requestDTO.setRandomCode(randomCode);
        requestDTO.setImageCode(imageCode);
        frontLoginConverter.validateUserPassword(requestDTO);
        LoginSuccessResultBO loginSuccessResultBO = userLoginService.getJwtToken(requestDTO.getUserName(), requestDTO.getPassword(),tenantCode);
        return frontLoginConverter.modelToResponse(loginSuccessResultBO);
    }
}